/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Others;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Others.MD5Convertor;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Neves
 */
@WebServlet(name = "CookieWriterReader", urlPatterns = {"/CookieWriterReader"})
public class CookieWriterReader extends HttpServlet {

    private Cookie[] cookies;
    private String WantedCookieValue;
    private String WantedCookieName;
    private String ToCreateCookie;
    private String definedCookie;
    private Cookie cookie;

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, NoSuchAlgorithmException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        this.definedCookie = new String();
        this.WantedCookieValue = new String();   /// HERE IS WHERE WE PUT THE COOKIE TO SEARCH -- USERNAME and PASSWORD
        this.WantedCookieName = new String();   /// HERE IS WHERE WE PUT THE COOKIE NAME 
        this.cookies = request.getCookies();  // get all cookies

        //GET the Cookies
        definedCookie = this.GetCookie();

        if (definedCookie == null) //MUST THEN CREATE ONE
        {
            this.SetCookie();
            response.addCookie(cookie);
        }


        try {
            /* TODO output your page here. You may use following sample code. */
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet CookieWriterReader</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet CookieWriterReader at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        } finally {
            out.close();
        }
    }

    public String GetCookie() {
        String sessionid = null;

        if (this.cookies != null) {
            for (int i = 0; i < this.cookies.length; i++) {
                if (this.cookies[i].getName().equals(this.WantedCookieValue)) {
                    sessionid = this.cookies[i].getValue();
                    return sessionid;
                }
            }
        }

        return sessionid;
    }

    public void SetCookie() throws NoSuchAlgorithmException, UnsupportedEncodingException {
        String HASH = new String();
        String UserPass = new String();
        MD5Convertor MD5convertor;



        MD5convertor = new MD5Convertor();
        HASH = MD5convertor.Md5ConversionToString(this.WantedCookieValue);

        cookie = new Cookie(this.WantedCookieName, this.WantedCookieValue);

        //cookie arguments
        cookie.setValue(HASH);
        cookie.setComment("This is the authentication Cookie");
        //this.setDomain("thehive.com");
        cookie.setMaxAge(3600);  //one hour
        cookie.setPath("/AuthenticatedUser");
        // cookie.setSecure(true);
        cookie.setVersion(0);

    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(CookieWriterReader.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(CookieWriterReader.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
